package net.pws.oos.biz.query.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.pws.common.util.DateUtils;
import net.pws.common.persistence.IPage;
import net.pws.common.persistence.Page;
import net.pws.common.persistence.QueryRepository;
import net.pws.oos.biz.model.Checkin;
import net.pws.oos.biz.model.Organization;
import net.pws.oos.biz.query.CheckinFinder;
import net.pws.oos.biz.query.parameter.CheckinQueryParameter;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings("unchecked")
public class DefaultCheckinFinder extends AbstractFinder implements CheckinFinder {

	public List<Checkin> list(String userId, Date start, Date end) {
		String hql = QueryRepository.getInstance().get("hql.listCheckin");
		Object[] params = new Object[] { Checkin.COMPLETED_STATUS, userId,
				start, end };
		return entityManager.findList(hql, params);
	}

	public List<Checkin> list(CheckinQueryParameter queryParameter) {
		StringBuilder hql = new StringBuilder(QueryRepository.getInstance().get("hql.listCheckin1"));
		StringBuilder hql2 = new StringBuilder("select count(*) from Checkin c where 1= 1 ");
		List<Object> params = new ArrayList<Object>();
		if (StringUtils.isNotBlank(queryParameter.getExecPersonId())) {
			hql.append(" and c.executePerson.id=? ");
			hql2.append(" and c.executePerson.id=? ");
			params.add(queryParameter.getExecPersonId());
		}
		if (StringUtils.isNotBlank(queryParameter.getStatus())) {
			hql.append(" and c.status=? ");
			hql2.append(" and c.status=? ");
			params.add(queryParameter.getStatus());
		}
		hql.append(" order by c.locateDate desc ");

		Page<Checkin> page = (Page<Checkin>) entityManager.findPage(hql2.toString(),
				hql.toString(), params.toArray(), queryParameter.getStart(),
				queryParameter.getLimit());
		return page.getData();
	}

	public boolean hasCheckin(String userId, String type, Date date) {
		String hql = QueryRepository.getInstance().get("hql.countCheckin");
		Object[] params = new Object[] { userId, type,
				DateUtils.getDateStart(date), DateUtils.getDateEnd(date) };
		Number count = (Number) entityManager.findFirst(hql, params);
		return count.intValue() > 0;
	}

	public Checkin get(String id) {
		String hql = QueryRepository.getInstance().get("hql.getCheckin");
		return (Checkin) entityManager.findFirst(hql, new Object[] { id });
	}

	public int countCheckin(CheckinQueryParameter queryParameter) {
		StringBuilder hql = new StringBuilder("select count(c.id) from Checkin c where 1=1 ");
        List<Object> params = new ArrayList<Object>();
        buildCheckinQueryRequest(queryParameter, hql, params);
        
        Number count = (Number) entityManager.findFirst(hql.toString(),
                                                        params.toArray());
        return count.intValue();
	}
	
	public List<Map> getCheckinList(CheckinQueryParameter queryParameter, int start, int limit) {
//		StringBuilder hql = new StringBuilder(QueryRepository.getInstance()
//				.get("hql.getTaskList")).append(" where c.parent is null ");
		StringBuilder hql = new StringBuilder(QueryRepository.getInstance().get("hql.getCheckinList")).append(" where  1= 1 ");
		List<Object> params = new ArrayList<Object>();
		buildCheckinQueryRequest(queryParameter, hql, params);
 
		// 排序
		if (Checkin.IN_PROGRESS_STATUS.equals(queryParameter.getStatus())) {
			hql.append(" order by c.createDateTime desc");
		} else if (Checkin.COMPLETED_STATUS.equals(queryParameter.getStatus())) {
			hql.append(" order by c.locateDate desc");
		} else {
			hql.append(" order by c.createDateTime desc");
		}

		IPage<Map> page = entityManager.findPage(hql.toString(),
				params.toArray(), start, limit);
		return page.getData();
	}
	
	/**
     * 
     * @param queryParameter
     * @param hql
     * @param params
     */
    private void buildCheckinQueryRequest(CheckinQueryParameter queryParameter,
                                       StringBuilder hql,
                                       List<Object> params) {
        if (queryParameter == null) {
            return;
        }
        if (StringUtils.isNotEmpty(queryParameter.getExecPersonId())) {
            hql.append(" and c.executePerson.id=? ");
            params.add(queryParameter.getExecPersonId());
        }
//        if (StringUtils.isNotEmpty(queryParameter.getExecPersonIds())) {
//            hql.append(" and c.executePerson.id in (");
//            hql.append(queryParameter.getExecPersonIds()).append(") ");
//        }
        if (StringUtils.isNotEmpty(queryParameter.getStatus())) {
            hql.append(" and c.status=? ");
            params.add(queryParameter.getStatus());
        }        
        
        if (StringUtils.isNotEmpty(queryParameter.getExecOrganId())) {
            Organization org = entityManager.find(Organization.class,
                                                  queryParameter.getExecOrganId());
            if (org != null) {
                hql.append(" and c.executeOrganization.innerCode like ?");
                params.add(org.getInnerCode() + "%");
            }
        }
        
//        // 定位时间
        if (queryParameter.getStartDate() != null) {
            hql.append(" and c.locateDate>=? ");
            params.add(queryParameter.getStartDate());
        }
        if (queryParameter.getEndDate() != null) {
            hql.append(" and c.locateDate<? ");
            params.add(DateUtils.addDay(queryParameter.getEndDate(), 1));
        }
        // 创建时间
//        if (queryParameter.getStartDate() != null) {
//            hql.append(" and c.createDateTime>=? ");
//            params.add(queryParameter.getStartDate());
//        }
//        if (queryParameter.getEndDate() != null) {
//            hql.append(" and c.createDateTime<? ");
//            params.add(DateUtils.addDay(queryParameter.getEndDate(), 1));
//        }
        
//        // 创建时间
//        if (queryParameter.getCreateStartDate() != null) {
//            hql.append(" and c.createDateTime>=? ");
//            params.add(queryParameter.getCreateStartDate());
//        }
//        if (queryParameter.getCreateEndDate() != null) {
//            hql.append(" and c.createDateTime<? ");
//            params.add(DateUtils.addDay(queryParameter.getCreateEndDate(), 1));
//        }
        
//        // 定位时间
//        if (queryParameter.getLocateStartDate() != null) {
//            hql.append(" and c.locateDate>=? ");
//            params.add(queryParameter.getLocateStartDate());
//        }
//        if (queryParameter.getLocateEndDate() != null) {
//            hql.append(" and c.locateDate<? ");
//            params.add(DateUtils.addDay(queryParameter.getLocateEndDate(), 1));
//        }
//        
//        if (queryParameter.getDataScope() == DataScope.Inside) {
//            hql.append(" and c.sourceSystem is null and c.sourceId is null ");
//        }
//        else if (queryParameter.getDataScope() == DataScope.Outside) {
//            hql.append(" and c.sourceSystem is not null and c.sourceId is not null ");
//        }
//        
//        if (StringUtils.isNotBlank(queryParameter.getCreateType())) {
//            hql.append(" and c.createType=? ");
//            params.add(queryParameter.getCreateType());
//        }      
    }

}
